package com.cqupt.scanning.system.acl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cqupt.scanning.handler.exception.MyException;
import com.cqupt.scanning.system.acl.entity.AclPermission;
import com.cqupt.scanning.system.acl.entity.AclUser;
import com.cqupt.scanning.system.acl.service.AclPermissionService;
import com.cqupt.scanning.system.acl.service.AclRoleService;
import com.cqupt.scanning.system.acl.service.AclUserService;
import com.cqupt.scanning.system.acl.service.IndexService;
import com.cqupt.scanning.system.utils.common.PasswordEncryption;
import com.cqupt.scanning.system.utils.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.security.acl.Acl;
import java.util.List;

@Service
public class IndexServiceImpl implements IndexService {

    private AclUserService aclUserService;
    private AclRoleService aclRoleService;
    private AclPermissionService aclPermissionService;
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public IndexServiceImpl(AclUserService aclUserService, AclRoleService aclRoleService,
                            RedisTemplate<String, Object> redisTemplate, AclPermissionService aclPermissionService) {
        this.aclUserService = aclUserService;
        this.aclRoleService = aclRoleService;
        this.redisTemplate = redisTemplate;
        this.aclPermissionService = aclPermissionService;
    }

    @Override
    public R getUserInfo() {
        JSONObject user = new JSONObject();
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        AclUser aclUser = aclUserService.getOne(new QueryWrapper<AclUser>().eq("username", username));
        if (ObjectUtil.isNull(aclUser)) throw new MyException(20001, "The current user does not exist");

        List<String> roleNameList = aclRoleService.selectRoleByUserId(aclUser.getId());
        if (roleNameList.size() <= 0) roleNameList.add(""); // 无角色，返回空角色

        List<String> permissionValueList = aclPermissionService.selectPermissionValueByUserId(aclUser.getId());
        redisTemplate.opsForValue().set(username, permissionValueList); // 缓存有则覆盖，无则写入最新

        user.put("username", aclUser.getUsername());
        user.put("type", aclUser.getType());
        user.put("nickname", aclUser.getNickName());
        user.put("phone", aclUser.getPhone());
        user.put("email", aclUser.getEmail());
        user.put("remark", aclUser.getRemark());
        user.put("createTime", aclUser.getCreateTime());
        user.put("updateTime", aclUser.getUpdateTime());
        user.put("roles", roleNameList);
        user.put("permissionValueList", permissionValueList);
        return R.ok().data("user", user);
    }

    @Override
    public R getPermissionMenu(String username) {
        AclUser aclUser = aclUserService.selectByUsername(username);
        List<AclPermission> permissionList = aclPermissionService.selectPermissionByUserId(aclUser.getId());
        return R.ok().data("permissionList", permissionList);
    }

    @Override
    public R updatePasswordByUser(String oldPassword,String newPassword,String qyPassword) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        AclUser aclUser = aclUserService.getOne(new QueryWrapper<AclUser>().eq("username", username));

        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();

        if (!bcryptPasswordEncoder.matches(oldPassword,aclUser.getPassword())){    //比对是否与旧密码相等，有无权限
            return R.error().message("密码不正确");
        }
//        else if (aclUser.getNote().equals("0")) {
//            return R.error().message("无权限");
//        }
        else if (bcryptPasswordEncoder.matches(oldPassword,aclUser.getPassword()) && newPassword.equals(qyPassword) && !StrUtil.isEmpty(newPassword) && !StrUtil.isEmpty(qyPassword)) {
            aclUser.setPassword(PasswordEncryption.execute(newPassword.trim()));
            aclUserService.update(aclUser,new QueryWrapper<AclUser>().eq("id",aclUser.getId()));
            return R.ok().data("aclUser",aclUser).message("密码修改成功");
        }
        return R.error().message("修改异常");


    }

}
